package com.wiki.gds.base.security.admin.core;

import com.wiki.gds.base.security.admin.utils.SecurityUtil;
import com.wiki.gds.base.security.common.model.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.Map;

public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) o;
        String url= fi.getHttpRequest().getRequestURI();
            SecurityUser securityUser= SecurityUtil.getSecurityUser();
            for(Map resource:securityUser.getResourceList()){
                if(antPathMatcher.match((String)resource.get("url"),url)){
                    return SecurityConfig.createList((String)resource.get("name"));
                }
            }
        //没有匹配到,默认是要登录才能访问
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
